import Database from '@tauri-apps/plugin-sql';
import {resourceDir } from '@tauri-apps/api/path';

let dbInstance: Database | null = null;

export async function getDB() {
    if (dbInstance) {
        return dbInstance;
    }
    
    // 获取应用数据目录和资源目录
   // const appDataDirPath = await appDataDir();
    const resourceDirPath = await resourceDir();
 //   const dbPath = `${appDataDirPath}/_up_/dolphin.db`;
    const resourceDbPath = `${resourceDirPath}/_up_/public/dolphin.db`;
   // console.log('appDataDirPath', appDataDirPath);
   // console.log('resourceDirPath', resourceDirPath);
   // console.log('dbPath', dbPath);
   // console.log('resourceDbPath', resourceDbPath);
  //  console.log('exists', await exists(dbPath));
 //   console.log('exists', await exists(resourceDbPath));
    // 检查数据库文件是否存在，如果不存在则从资源目录复制
    //if (!(await exists(dbPath))) {
    //    // 如果应用数据目录中没有数据库文件，则从资源目录复制
    //    if (await exists(resourceDbPath)) {
   //         await copyFile(resourceDbPath, dbPath);
     //   }
  //  }
    
    // 使用 appData 协议加载数据库，这是 Tauri SQL 插件允许的方式
    dbInstance = await Database.load(`sqlite:${resourceDbPath}`);
    //    dbInstance = await Database.load(`sqlite:/data/workdata/git/code/zwm/xplk/public/dolphin.db`);
   // dbInstance = await Database.load(`sqlite:E:/tauri/xplk/public/dolphin.db`);
   // dbInstance = await Database.load(`sqlite:E:/workdata/git/code/zwm/xplk/public/dolphin.db`);
    return dbInstance;
}

export async function execute(sql: string, params?: any[]) {
    const db = await getDB();
    return db.execute(sql, params);
}

export async function select<T>(sql: string, params?: any[]) {
    const db = await getDB();
    return db.select<T>(sql, params);
}